package com.foo.ajax;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

public class CalcPage extends WebPage {
	private int num;
	private int result;
	private Label r;
	private FeedbackPanel feedback;
	private WebMarkupContainer helpContent;

	public CalcPage() {
		feedback = new FeedbackPanel("feedback");
		feedback.setOutputMarkupId(true);
		add(feedback);
		Form<Void> f = new Form<Void>("f");
		add(f);
		TextField<Integer> numField = new TextField<Integer>("num",
				new PropertyModel<Integer>(this, "num"));
		f.add(numField);
		numField.add(new AjaxFormSubmitBehavior(f, "onkeyup") {

			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target) {
				result = 2 * num;
				target.add(r);
				target.add(feedback);
			}

			@Override
			protected void onError(AjaxRequestTarget target) {
				target.add(feedback);
			}

		});
		r = new Label("r", new PropertyModel<Integer>(this, "result"));
		r.setOutputMarkupId(true);
		add(r);
		
		/* Another approach:
		 * http://api.jquery.com/click/
		 */
		AjaxLink<Void> help = new AjaxLink<Void>("help") {

			private static final long serialVersionUID = 1L;

			@Override
			public void onClick(AjaxRequestTarget target) {
				helpContent.setVisible(!helpContent.isVisible());
				target.add(helpContent);
			}
		};
		add(help);
		helpContent = new WebMarkupContainer("helpContent");
		helpContent.setVisible(false);
		helpContent.setOutputMarkupPlaceholderTag(true);
		add(helpContent);
	}
}